<template>
  <config-template
    ref="configTemplateRef"
    :fields="msgConfigFields"
    :title="$t('form.configParams.configTemplateVariables')"
    @close="showMsgConfigTemplate = false"
    @submit="handleSaveMsgTemplateConfig"
  />
</template>

<script lang="ts" name="ConfigTemplate" setup>
import { onMounted, ref, watch } from "vue";
import { FieldItem } from "@/api/project/form";
import { i18n } from "@/i18n";
import ConfigTemplate from "@/views/form/publish/TodoForm/ConfigTemplate.vue";
import { useFormWorkflow } from "@/stores/formWorkflow";
import { storeToRefs } from "pinia";
import { getExtSettingByType, saveExtSetting } from "@/api/project/extSetting";
import { MessageUtil } from "@/utils/messageUtil";
import { useRoute } from "vue-router";

const msgConfigFields = ref<FieldItem[]>([
  {
    label: i18n.global.t("form.todoForm.writeLink"),
    value: "link"
  },
  {
    label: i18n.global.t("form.todoForm.userNickName"),
    value: "userNickName"
  },
  {
    label: i18n.global.t("form.todoForm.formName"),
    value: "processName"
  }
  // {
  //   label: i18n.global.t("form.todoForm.uniqueId"),
  //   value: "uniqueKey"
  // }
]);

const msgType = "approvalMsgTemplate";

const msgConfig = ref({});
const route = useRoute();
const formKey = ref(route.query.key as string);
onMounted(() => {
  getExtSettingByType(msgType, formKey.value).then(res => {
    if (res.data && res.data.settings) {
      msgConfig.value = JSON.parse(res.data.settings);
    }
  });
});

const handleSaveMsgTemplateConfig = (config: any) => {
  saveExtSetting({
    settings: JSON.stringify(config),
    type: msgType,
    formKey: formKey.value
  }).then(() => {
    showMsgConfigTemplate.value = false;
    MessageUtil.success(i18n.global.t("common.saveSuccess"));
  });
};

const configTemplateRef = ref<any>(null);

const formWorkflowStore = useFormWorkflow();
const { showMsgConfigTemplate } = storeToRefs(formWorkflowStore);

watch(
  () => showMsgConfigTemplate.value,
  () => {
    if (showMsgConfigTemplate.value) {
      configTemplateRef.value!.show(msgConfig.value || {});
    }
  }
);
</script>
<style lang="scss" scoped></style>
